package com.example.edianzu.somur.utils.view;

import android.content.ActivityNotFoundException;
import android.content.ContentValues;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Build;
import android.provider.MediaStore;
import android.support.annotation.NonNull;
import android.support.v4.content.ContextCompat;
import android.util.Log;

import com.example.edianzu.somur.App;
import com.example.edianzu.somur.R;
import com.example.edianzu.somur.api.constans.AppContents;
import com.example.edianzu.somur.utils.content.L;
import com.example.edianzu.somur.utils.content.SharedPreferencesUtils;
import com.facebook.drawee.drawable.ScalingUtils;
import com.facebook.drawee.view.SimpleDraweeView;
import com.yalantis.ucrop.UCrop;

import java.io.File;

/**
 * author：风不会停息 on 2017/8/2 13:16
 * mailbox：yh131412hys@163.com
 * project：Somur
 * tel：13295355900
 * describe：
 */

public class MediaUtils {

    public static final int ALBUMS_REQUEST_CODE = 0x1012;
    public static final int CAMERA_REQUEST_CODE = 0x1112;
    public static final int CROP_REQUEST_CODE = 0x1212;
    public static final int VIDEO_REQUEST_CODE = 0x1213;
    private final String USER_HEAD = "userHead.jpg";
    private BaseActivity mContext;
    private Uri resultUri;
    private File headFile;

    public MediaUtils(BaseActivity context) {
        this.mContext = context;
    }


    /**
     * @author XQY
     * @function 打开相册
     * @since 2016/12/20 下午3:46
     **/
    public void pickGallery() {
        Intent intent = new Intent();
        intent.setType("image/*");
        intent.setAction(Intent.ACTION_GET_CONTENT);
        intent.addCategory(Intent.CATEGORY_OPENABLE);
        mContext.startActivityForResult(Intent.createChooser(intent, mContext.getString(R.string.app_name)), ALBUMS_REQUEST_CODE);
    }

    /**
     * @author XQY
     * @function 照相
     * @since 2016/12/20 下午3:42
     **/
    public void TakePhoto() {
        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        ContentValues values = new ContentValues();
        Uri photoUri = BaseActivity.getAppContext().getContentResolver()
                .insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
        intent.putExtra(MediaStore.EXTRA_OUTPUT, photoUri.toString());
        try {
            intent.putExtra("return-data", true);
            //mContext.setHintMessage("");
            mContext.startActivityForResult(intent, CAMERA_REQUEST_CODE);

        } catch (ActivityNotFoundException e) {
            e.printStackTrace();
        }

    }

    public void startCropActivity(@NonNull Intent data) {
        if (data == null) {
//            mContext.setHintMessage(R.string.head_setting_failed);
            return;
        }
        Uri uri = data.getData();
        if (uri == null) {
            Bitmap bitmap = (Bitmap) data.getExtras().get("data");
            if (bitmap != null) {
                uri = Uri.parse(MediaStore.Images.Media.insertImage(mContext.getContentResolver(), bitmap, null, null));
            }
        }
        headFile = new File(App.IMAGE_DIR, System.currentTimeMillis() + USER_HEAD);

        if (headFile.exists()) {
            headFile.mkdir();
        }

        Log.e("MediaUtils", headFile.getAbsolutePath());

        UCrop uCrop = UCrop.of(uri, Uri.fromFile(headFile));
        uCrop = basisConfig(uCrop);
        uCrop = advancedConfig(uCrop);
        uCrop.start(mContext, CROP_REQUEST_CODE);
    }

    /**
     * @author XQY
     * @function 高级参数
     * @since 2016/12/21 下午3:55
     **/
    private UCrop advancedConfig(@NonNull UCrop uCrop) {
        UCrop.Options options = new UCrop.Options();
        options.setCompressionFormat(Bitmap.CompressFormat.PNG);
        options.setCircleDimmedLayer(true);
        options.setCropGridColumnCount(4);
        options.setCropGridRowCount(4);
        options.setImageToCropBoundsAnimDuration(1000);
        options.setToolbarColor(ContextCompat.getColor(mContext, R.color.black));
        options.setCompressionQuality(100);
        options.setHideBottomControls(true);
        options.setFreeStyleCropEnabled(true);
        return uCrop.withOptions(options);
    }

    /**
     * @author XQY
     * @function 基本参数
     * @since 2016/12/21 下午3:55
     **/
    private UCrop basisConfig(@NonNull UCrop uCrop) {
        uCrop = uCrop.useSourceImageAspectRatio();

        uCrop = uCrop.withAspectRatio(1, 1);

        try {
            int maxWidth = Integer.valueOf(60);
            int maxHeight = Integer.valueOf(60);
            if (maxWidth > 0 && maxHeight > 0) {
                uCrop = uCrop.withMaxResultSize(maxWidth, maxHeight);
            }
        } catch (NumberFormatException e) {
            L.e("Number please", e);
        }


        return uCrop;
    }

    /**
     * 此方法用于将剪切好的 图片放到 IV 中
     */
    public void setCropPicture(SimpleDraweeView imageView, Intent data) {
        if (data == null) {
            //mContext.setHintMessage(R.string.head_setting_failed);
            return;
        }
        resultUri = UCrop.getOutput(data);
        if (resultUri != null) {
            L.e(resultUri);
            SharedPreferencesUtils.put(App.getApp(), AppContents.USER_HEAD,resultUri);
        }
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
            imageView.setBackground(null);
        }
        imageView.getHierarchy().setActualImageScaleType(ScalingUtils.ScaleType.FOCUS_CROP);
        imageView.setPadding(0, 0, 0, 0);
        imageView.setImageURI(resultUri);

    }

    public File getUserHeadFile() {
        return headFile;
    }
}
